<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\admin\controller;

/**
 * Description of Judge
 *
 * @author wurong
 */
use think\Controller;
use think\Log;
class Judge extends Controller{
    public function __construct(\think\Request $request = null) {
        parent::__construct($request);
        $localpasswd = config('judge.passwd');
        $passwd=input('passwd');
        if($localpasswd!=$passwd){
            Log::write(request()->ip()."密码错误被阻止！");
            die('false');
        }
    }
    private function solutioninfo($id){
        $res=db('solution')->find($id);
        if(empty($res)) {
            return FALSE;
        }
        return $res;
    }
    /*
     * 获取用户某一题目状态
     * false 未通过
     * true 已通过
     */
    private function problemstatus($uid,$pid,$id){
        $condition['user_id']=$uid;
        $condition['problem_id']=$pid;
        $condition['solution_id']=['NEQ',$id];
        $res=db('solution')->where($condition)->find();
        if(empty($res)){
            return FALSE;
        }
        else {
            return true;
        }
    }

    private function addcoin($user,$num){
        db('users')->where('user_id',$user)->setInc('ojcoin', $num);
    }
    private function problemscore($pid){
        $res=db('problem')->find($pid);
        if(empty($res)){
            return 0;
        }
        else {
            return $res['score'];
        }
    }

    public function acproblem(){
        $id= input('id');
        $info= $this->solutioninfo($id);
        $staus= $this->problemstatus($info['user_id'], $info['problem_id'], $id);
        if($staus==FALSE){
            $num= $this->problemscore($info['problem_id']);
            $this->addcoin($info['user_id'], $num);
            Log::write("solution_id ".$info['solution_id']."  用户： ".$info['user_id']."获取".$num."个OJ币");
            return 'true';
        }
        else {
            Log::write("solution_id ".$info['solution_id']."  用户： ".$info['user_id']."早已经AC");
        }
    }
}
